package com.dayatang.product.webapp.action.product;

import java.util.Date;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.dao.DataIntegrityViolationException;

import com.dayatang.product.domain.Product;
import com.dayatang.product.webapp.action.BaseAction;

@Result(name = "success", type = "redirect", location = "/product/product-manage.action")
@ParentPackage(value = "web")
public class ProductSubmitAction extends BaseAction {

	private static final long serialVersionUID = 531877155510318778L;

	private Product product;
	
	private int result;
	
	public String execute() throws Exception {
		
		if (product != null) {
			product.setReleaseDate(new Date());
			productApplication.saveEntity(product);
		}
		
		return SUCCESS;
	}

	@Action(value = "/product/product-remove",results = {@Result(name = "success", type = "json")})
	public String removeProduct() {
		if (product.getId() > 0) {
			try {
				product = Product.get(Product.class, product.getId());
				if (product.getProductTrials().size() > 0) {
					result = ONE;
					return SUCCESS;
				}
				productApplication.removeEntity(product);
			} catch (DataIntegrityViolationException e) {
				result = 1;
			}
		}
		return SUCCESS;
	}
	
	@JSON(serialize = false)
	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public int getResult() {
		return result;
	}

	public void setResult(int result) {
		this.result = result;
	}
	
}
